<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">  <!-- 设置字符编码为 UTF-8 -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>打卡墙</title>
    <link rel="icon" href="/img/favicon.png" type="image/png">

    <script src="libs/axios.min.js"></script>
    <script src="libs/vue.global.js"></script>
    <script src="libs/index.full.js"></script>
    <script src="js/navbar.js"></script>
    <link rel="stylesheet" href="libs/index.css">
    <link rel="stylesheet" href="css/navbar.css">
    <link rel="stylesheet" href="css/record.css">

</head>
<body>
<div id="app" class="full_container">
    <div id="navbar" class="navbar"></div>
    <div class="app_container--main">
        <div class="app_container--left"></div>
        <div class="app_container--middle">
<!--            &lt;!&ndash; Calendar Section &ndash;&gt;-->
<!--            <div class="calendar">-->
<!--                <div v-for="day in calendarDays" :key="day.date"-->
<!--                     class="day" :class="{'checked': day.checked}" @click="toggleCheckIn(day)">-->
<!--                    {{ day.date }}-->
<!--                </div>-->
<!--            </div>-->

            <!-- Input Section -->
            <div class="input_section">
                <textarea v-model="messageContent" placeholder="请输入你的打卡内容..." @keyup.enter="submitMessage"></textarea>
                <button @click="getAddPoints">提交内容</button>
            </div>

            <!-- Message Wall Section -->
            <div class="message_wall">
                <div v-for="message in messages" :key="message.id" class="item">
                    <img :src="message.avatar" class="item-avatar">
                    <div class="item-right">
                        <div class="content">{{message.content}}</div>
                        <div class="item-footer">
                            <span>{{ message.area }}</span>
                            <span>{{ message.datetime }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="app_container--right"></div>
    </div>
</div>

</body>
<script>
    const {createApp} = Vue;

    const {ElMessage} = ElementPlus;

    createApp({
        data(){
            return{
                messageContent: '',
                messages: [],
                currentUserId: 0,
                addPoints:0,
            }
        },
        mounted() {
            this.getCurrentUser();
        },
        methods: {
            getCurrentUser() {
                axios.get('http://localhost:8080/chat/currentUser')
                    .then(response => {
                        if (response.data.code === 200) {
                            this.currentUserId = response.data.data.id;
                            console.log(this.currentUserId);
                            this.getData(); // 在这里调用
                        } else {
                            console.warn("未登录，跳转到登录页");
                            window.location.href = "/login.html"; // 重定向到登录页
                        }
                    })
                    .catch(error => console.error("获取当前用户失败:", error));
            },
            getData(){
                const now = new Date();
                const year = now.getFullYear();
                const month = now.getMonth() + 1; // 注意：getMonth() 从 0 开始
                const userId = this.currentUserId;
                axios.get(`http://localhost:8080/records/content`, {
                    params: {
                        userId: userId,
                        year: year,
                        month: month  }
                })
                    .then(response => {
                        if(response.data.code === 200){
                            this.messages = response.data.data.map(message => {
                                const date = new Date(message.datetime);

                                // 将日期格式化为需要的格式（例如：yyyy-MM-dd）
                                const formattedDate = date.toLocaleString();  // 你可以根据需要调整格式

                                // 返回更新的对象
                                return {
                                    ...message,
                                    datetime: formattedDate
                                };
                            });
                            console.log(this.messages)
                        }
                    })
                    .catch(error => {
                        console.error('获取签到次数失败', error);
                    });
            },
            getAddPoints(){
                const now = new Date();
                const year = now.getFullYear();
                const month = now.getMonth() + 1; // 注意：getMonth() 从 0 开始

                axios.get(`http://localhost:8080/records/count`, {
                    params: { year, month }
                })
                    .then(response => {
                        const count = response.data.data;

                        if (count >= 20) {
                            this.addPoints = 10;
                        } else if (count >= 10) {
                            this.addPoints = 5;
                        } else {
                            this.addPoints = 1;
                        }
                        this.submitMessage();
                    })
                    .catch(error => {
                        console.error('获取签到次数失败', error);
                        this.addPoints = 0; // 失败时默认给 0 分
                    });
            },
            submitMessage() {
                if (!this.messageContent.trim()) {
                    ElMessage.warning('内容不能为空');
                    return;
                }
                const now = new Date();
                const year = now.getFullYear();
                const month = String(now.getMonth() + 1).padStart(2, '0');
                const day = String(now.getDate()).padStart(2, '0');
                const datetime = `${year}-${month}-${day}`;
                axios.post('http://localhost:8080/records', {
                    datetime: datetime,
                    content: this.messageContent,
                    userId: this.currentUserId,
                    isSignIn: 1,
                    addPoints: this.addPoints,
                })
                    .then(response => {
                         if(response.data.code === 200){
                             ElMessage.success("打卡成功");
                             this.messageContent = '';
                             this.getData();
                             this.change();
                         }
                    })
                    .catch(error => console.error("打卡失败", error));
            },
            formatDateTime(date) {
                const pad = n => (n < 10 ? '0' + n : n);
                return date.getFullYear() + '-' +
                    pad(date.getMonth() + 1) + '-' +
                    pad(date.getDate()) + ' ' +
                    pad(date.getHours()) + ':' +
                    pad(date.getMinutes()) + ':' +
                    pad(date.getSeconds());
            },
            change(){
                const createTime = this.formatDateTime(new Date())

                const data = {
                    content: "打卡签到",
                    userId: this.currentUserId,
                    createTime: createTime,
                    pointsChange: "+" + this.addPoints
                }
                console.log("请求数据：", data);
                axios.post('http://localhost:8080/pointsRecords',data)
                    .then(response =>{
                        if(response.data.code === 200){
                            console.log("积分+",this.addPoints)
                        }
                    })
                    .catch(error => console.error("积分记录失败",error))
            }
        }
    }).use(ElementPlus).mount('#app');
</script>
</html>